/*
* 运输进度
* */

import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/statistical_analysis_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/selectRow_widget.dart';
import 'package:center_beijing/widgets/select_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:convert';

class TranProgress extends StatefulWidget {
  @override
  _TranProgressState createState() => _TranProgressState();
}

class _TranProgressState extends State<TranProgress>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  final List<Tab> myTabs = <Tab>[
    Tab(text: '日期维度'),
    Tab(text: '订单维度'),
  ];
  TabController _tabController;
  int currentIndex = 0;
  var selectTime = Utils.timeUtil(DateTime.now().toIso8601String());
  SelectItems selectType = SelectItems(label: '方量(m³)', value: '1'); //1方量  2数量
  SelectItems selectType2 = SelectItems(label: '方量(m³)', value: '1'); //1方量  2数量

  var selectTimeRangeStart = Utils.timeUtil(DateTime.now().subtract(Duration(days:29)).toIso8601String());
  var selectTimeRangeEnd = Utils.timeUtil(DateTime.now().toIso8601String());

  bool chartLoading = true;
  var charts = [];
  var dataSource = Map();
  var dataSource2 = Map();
  List<SelectItems> projectNameList = [];
  SelectItems selectProject = SelectItems();


  var _dateSelectText= Utils.timeUtil(DateTime.now().subtract(Duration(days:29)).toIso8601String())+'至'+ Utils.timeUtil(DateTime.now().toIso8601String());

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
    this.getInfo();
    this.getOrders();
    // this.getChartByOrder();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  getInfo() async {
    var pass = {
      'projectId': GlobalConfig.selectFactory.value,
      'radioValueChart': selectType.value,
      'date': selectTime,

    };
    var result = await getTranChart(pass);
    if (result != null) {
      this.setState(() {
        dataSource = result;
        charts = result['data'];
      });
    }
  }

  getChartByOrder() async {
    var pass = {
      'projectId': GlobalConfig.selectFactory.value,
      'radioValueTable': selectType2.value,
      'orderName': selectProject.label,
      'start':selectTimeRangeStart,
      'end':selectTimeRangeEnd
    };
    var result = await getTranChartByOrder(pass);
    if (result != null) {
      this.setState(() {
        dataSource2 = result;
      });
    }
  }

  /*
  * 获取订单列表
  * */
  getOrders() async {
    var pass = {'projectId': GlobalConfig.selectFactory.value};
    var result = await getOrderList(pass);
    if (result != null) {
      result.forEach((item) {
        projectNameList.add(SelectItems(
            label: item['orderName'], value: item['id'], dict: item));
      });

      this.setState(() {
        selectProject = projectNameList[0];
        this.getChartByOrder();
      });
    }
  }

  void showDateSelect() async {
    //显示时间选择器
    DateTimeRange selectTimeRange = await showDateRangePicker(
      //语言环境
        locale: Locale("zh","CH"),
        context: context,
        //开始时间
        firstDate: DateTime(2020, 1),
        //结束时间
        lastDate: DateTime(2040, 1),
        cancelText: "取消",
        confirmText: "确定",
        //初始的时间范围选择
        initialDateRange: DateTimeRange(start: DateTime.parse(selectTimeRangeStart), end: DateTime.parse(selectTimeRangeEnd))
    );

    //选择结果中的开始时间
    DateTime selectStart = selectTimeRange.start;
    //选择结果中的结束时间
    DateTime selectEnd = selectTimeRange.end;

    this.selectTimeRangeStart = selectStart.year.toString() +
        '-' +
        (selectStart.month > 9
            ? selectStart.month.toString()
            : ('0' + selectStart.month.toString())) +
        '-' +
        (selectStart.day > 9
            ? selectStart.day.toString()
            : ('0' + selectStart.day.toString()));
    this.selectTimeRangeEnd = selectEnd.year.toString() +
        '-' +
        (selectEnd.month > 9
            ? selectEnd.month.toString()
            : ('0' + selectEnd.month.toString())) +
        '-' +
        (selectEnd.day > 9
            ? selectEnd.day.toString()
            : ('0' + selectEnd.day.toString()));
    //结果
    _dateSelectText = this.selectTimeRangeStart+'至'+this.selectTimeRangeEnd ;
    this.getChartByOrder();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            height: 40.h,
            color: Colors.white,
            child: DefaultTabController(
              length: 2,
              initialIndex: currentIndex,
              child: TabBar(
                controller: _tabController,
                onTap: (value) {
                  this.setState(() {
                    currentIndex = value;
                  });
                },
                indicatorColor: Colors.red,
                tabs: myTabs,
                labelColor: Styles.BlueColor,
                unselectedLabelColor: Styles.LeftTitleColor,
                // add it here
                indicator:
                    MaterialIndicator(color: Styles.BlueColor, height: 1),
              ),
            ),
          ),
          Expanded(child: SingleChildScrollView(
            child: currentIndex == 0
                ? Column(
              children: [

                Container(
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  color: Colors.white,
                  padding: EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                  child: SelectRow(
                      titleFont: Styles.MiddleFont17,
                      require: true,
                      selectType: DateMode.YMD,
                      title: '日期选择',
                      rightText: selectTime,
                      selectCallback: (value) {
                        this.setState(() {
                          selectTime = value;
                          this.getInfo();
                        });
                      }),
                ),
                Container(
                  color: Colors.white,
                  child: CustomRadio(
                    currentItem: selectType,
                    top: 0,
                    selectList: [
                      SelectItems(label: '方量(m³)', value: '1'),
                      SelectItems(label: '数量(片)', value: '2')
                    ],
                    selectCallback: (item) {
                      this.setState(() {
                        selectType = item;
                        this.getInfo();
                      });
                    },
                    title: '',
                  ),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.all(Styles.spacing8),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border(
                                top: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                right: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                bottom: BorderSide(
                                    color: Styles.LineColor, width: 1))),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                this.dataSource['viewTransportCard'] != null
                                    ? this
                                    .dataSource['viewTransportCard']
                                ['transportNum']
                                    .toString()
                                    : '--',
                                style: TextStyle(
                                    color: Styles.OrangeColor,
                                    fontSize: Styles.BigFont26),
                              ),
                            ),
                            Container(
                              child: Text(
                                '运输单数(个)',
                                style: TextStyle(
                                    color: Styles.LeftTitleColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border(
                                top: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                right: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                bottom: BorderSide(
                                    color: Styles.LineColor, width: 1))),
                        padding: EdgeInsets.all(Styles.spacing8),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                this.dataSource['viewTransportCard'] != null
                                    ? (selectType.value == '1'
                                    ? this
                                    .dataSource['viewTransportCard']
                                ['volume']
                                    .toString()
                                    : this
                                    .dataSource['viewTransportCard']
                                ['quantity']
                                    .toString())
                                    : '--',
                                style: TextStyle(
                                    color: Styles.OrangeColor,
                                    fontSize: Styles.BigFont26),
                              ),
                            ),
                            Container(
                              child: Text(
                                '构件总${selectType.value == '1'?'方量(m³)':'片数(个)'}',
                                style: TextStyle(
                                    color: Styles.LeftTitleColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border(
                                  top: BorderSide(
                                      color: Styles.LineColor, width: 1),
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          padding: EdgeInsets.all(Styles.spacing8),
                          child: Column(
                            children: [
                              Container(
                                child: Text(
                                  this.dataSource['averageVolume'] != null
                                      ? this
                                      .dataSource['averageVolume']
                                      .toString()
                                      : '--',
                                  style: TextStyle(
                                      color: Styles.OrangeColor,
                                      fontSize: Styles.BigFont26),
                                ),
                              ),
                              Container(
                                child: Text(
                                  '平均方量(m³)',
                                  style: TextStyle(
                                      color: Styles.LeftTitleColor,
                                      fontSize: Styles.NormalFont),
                                ),
                              ),
                            ],
                          ),
                        ))
                  ],
                ),
                Container(
                  child: Stack(
                    children: [
                      Echarts(
                        onLoad: (value) {
                          LogUtil.d(value);
                          this.setState(() {
                            chartLoading = false;
                          });
                        },
                        option: '''
                    {
        title: {
          text: '类型分布',
          left: 'left',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'item'
          // formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          bottom: '10%',
          right: '1%',
          type: 'scroll',
          orient: 'vertical'
        },
        series: [
          {
            name: '构件类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                // show: true,
                fontSize: '40',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: ${json.encode(this.charts)}
          }
        ]
      }
                  ''',
                        extraScript: '''
                    chart.on('click', (params) => {
                      if(params.componentType === 'series') {
                        Messager.postMessage(JSON.stringify({
                          type: 'select',
                          payload: params.dataIndex,
                        }));
                      }
                    });
                  ''',
                        onMessage: (String message) {
                          LogUtil.d(message);
                          // Map<String, Object> messageAction = jsonDecode(message);
                          // print(messageAction);
                          // if (messageAction['type'] == 'select') {
                          //   final item = _data1[messageAction['payload']];
                          //   _scaffoldKey.currentState.showSnackBar(
                          //     SnackBar(
                          //       content: Text(item['name'].toString() + ': ' + item['value']),
                          //       duration: Duration(seconds: 2),
                          //     ));
                          // }
                        },
                      ),
                      chartLoading
                          ? Container(
                        alignment: Alignment.center,
                        child: CircularProgressIndicator(),
                      )
                          : Container()
                    ],
                  ),
                  width: 1.sw,
                  height: 250.h,
                ),
              ],
            )
                : Column(
              children: [
                Container(
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  color: Colors.white,
                  child: SelectWidget(
                    title: '日期选择',
                    rightText: _dateSelectText,
                    require: true,
                    selectCallback: () async {
                      this.showDateSelect();
                    },
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  child: CustomSelectWidget(
                    require: true,
                    rightText: selectProject.label != null
                        ? selectProject.label
                        : '请选择',
                    items: projectNameList,
                    selectCallback: (value) {
                      this.setState(() {
                        selectProject = value;
                        this.getChartByOrder();
                      });
                    },
                    title: '订单名称',
                  ),
                ),
                Container(
                  color: Colors.white,
                  child: CustomRadio(
                    top: 0,
                    currentItem: selectType2,
                    selectList: [
                      SelectItems(label: '方量(m³)', value: '1'),
                      SelectItems(label: '数量(片)', value: '2')
                    ],
                    selectCallback: (item) {
                      this.setState(() {
                        selectType2 = item;
                        this.getChartByOrder();
                      });
                    },
                    title: '',
                  ),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.all(Styles.spacing8),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border(
                                top: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                right: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                bottom: BorderSide(
                                    color: Styles.LineColor, width: 1))),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                this.dataSource2['viewTransportCard'] !=
                                    null
                                    ? this
                                    .dataSource2['viewTransportCard']
                                ['transportNum']
                                    .toString()
                                    : '--',
                                style: TextStyle(
                                    color: Styles.OrangeColor,
                                    fontSize: Styles.BigFont26),
                              ),
                            ),
                            Container(
                              child: Text(
                                '运输单数(个)',
                                style: TextStyle(
                                    color: Styles.LeftTitleColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border(
                                top: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                right: BorderSide(
                                    color: Styles.LineColor, width: 1),
                                bottom: BorderSide(
                                    color: Styles.LineColor, width: 1))),
                        padding: EdgeInsets.all(Styles.spacing8),
                        child: Column(
                          children: [
                            Container(
                              child: Text(
                                this.dataSource2['viewTransportCard'] !=
                                    null
                                    ? (selectType2.value == '1'
                                    ? this
                                    .dataSource2[
                                'viewTransportCard']
                                ['volume']
                                    .toString()
                                    : this
                                    .dataSource2[
                                'viewTransportCard']
                                ['quantity']
                                    .toString())
                                    : '--',
                                style: TextStyle(
                                    color: Styles.OrangeColor,
                                    fontSize: Styles.BigFont26),
                              ),
                            ),
                            Container(
                              child: Text(
                                '构件总${selectType2.value == '1'?'方量(m³)':'片数(个)'}',
                                style: TextStyle(
                                    color: Styles.LeftTitleColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border(
                                  top: BorderSide(
                                      color: Styles.LineColor, width: 1),
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          padding: EdgeInsets.all(Styles.spacing8),
                          child: Column(
                            children: [
                              Container(
                                child: Text(
                                  this.dataSource2['averageVolume'] != null
                                      ? this
                                      .dataSource2['averageVolume']
                                      .toString()
                                      : '--',
                                  style: TextStyle(
                                      color: Styles.OrangeColor,
                                      fontSize: Styles.BigFont26),
                                ),
                              ),
                              Container(
                                child: Text(
                                  '平均方量(m³)',
                                  style: TextStyle(
                                      color: Styles.LeftTitleColor,
                                      fontSize: Styles.NormalFont),
                                ),
                              ),
                            ],
                          ),
                        ))
                  ],
                ),
                Container(
                  child: Stack(
                    children: [
                      Echarts(
                        onLoad: (value) {
                          LogUtil.d(value);
                          this.setState(() {
                            chartLoading = false;
                          });
                        },
                        option: '''
                    {
        title: {
          text: '运输单日期分布',
          left: 'left',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          }
        },
        calculable: true,
        grid: {
          // top: '12%',
          left: '5%',
          right: '5%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ${this.dataSource2['viewWarehouseChart'].map((e) {
                          return json.encode(e['createTime']);
                        }).toList()},
                       
          }
        ],
        yAxis: [
          {
            type: 'value',
            // name: '方量',
            axisLabel: {
              formatter: function (a) {
                a = +a
                return isFinite(a) ? echarts.format.addCommas(+a) : ''
              }
            }
          }
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 100
          }
        ],
        series: [
          {
            name: '',
            type: 'line',
            areaStyle: {},
            data: ${this.dataSource2['viewWarehouseChart'].map((e) {
                          return selectType2.value == '1'
                              ? e['volume']
                              : e['quantity'];
                        }).toList()}
          }
        ]
      }
                  ''',
                        extraScript: '''
                    chart.on('click', (params) => {
                      if(params.componentType === 'series') {
                        Messager.postMessage(JSON.stringify({
                          type: 'select',
                          payload: params.dataIndex,
                        }));
                      }
                    });
                  ''',
                        onMessage: (String message) {
                          LogUtil.d(message);
                          // Map<String, Object> messageAction = jsonDecode(message);
                          // print(messageAction);
                          // if (messageAction['type'] == 'select') {
                          //   final item = _data1[messageAction['payload']];
                          //   _scaffoldKey.currentState.showSnackBar(
                          //     SnackBar(
                          //       content: Text(item['name'].toString() + ': ' + item['value']),
                          //       duration: Duration(seconds: 2),
                          //     ));
                          // }
                        },
                      ),
                      chartLoading
                          ? Container(
                        alignment: Alignment.center,
                        child: CircularProgressIndicator(),
                      )
                          : Container()
                    ],
                  ),
                  width: 1.sw,
                  height: 250.h,
                ),
                Container(
                  child: Stack(
                    children: [
                      Echarts(
                        onLoad: (value) {
                          LogUtil.d(value);
                          this.setState(() {
                            chartLoading = false;
                          });
                        },
                        option: '''
                    {
        title: {
          text: '类型分布',
          left: 'left',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'item'
          // formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          bottom: '10%',
          right: '1%',
          type: 'scroll',
          orient: 'vertical'
        },
        series: [
          {
            name: '构件类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                // show: true,
                fontSize: '40',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: ${json.encode(this.dataSource2['data'])}
          }
        ]
      }
                  ''',
                        extraScript: '''
                    chart.on('click', (params) => {
                      if(params.componentType === 'series') {
                        Messager.postMessage(JSON.stringify({
                          type: 'select',
                          payload: params.dataIndex,
                        }));
                      }
                    });
                  ''',
                        onMessage: (String message) {
                          LogUtil.d(message);
                          // Map<String, Object> messageAction = jsonDecode(message);
                          // print(messageAction);
                          // if (messageAction['type'] == 'select') {
                          //   final item = _data1[messageAction['payload']];
                          //   _scaffoldKey.currentState.showSnackBar(
                          //     SnackBar(
                          //       content: Text(item['name'].toString() + ': ' + item['value']),
                          //       duration: Duration(seconds: 2),
                          //     ));
                          // }
                        },
                      ),
                      chartLoading
                          ? Container(
                        alignment: Alignment.center,
                        child: CircularProgressIndicator(),
                      )
                          : Container()
                    ],
                  ),
                  width: 1.sw,
                  height: 250.h,
                ),
              ],
            ),
          ))
        ],
      ),
    );
  }
}
